package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iwhalecloud.bss.kite.client.dto.cust.ContextCustDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.StartRentInfoModuleVO;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IDeliveryService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;

@Service
public class StartRentInfoAttrModuleHandler extends AbstractModuleHandler {


    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Autowired
    private IDeliveryService deliveryService;

    @Resource
    private IUnicomRegionService unicomRegionService;

    @Override
    public List<? extends ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {
        StartRentInfoModuleVO startRentInfo = ((SceneNewOfferSeneVO) context.getSceneVo()).getStartRentInfo();
        String moduleId = sceneModule.getKiteModule().getModuleId();
        String sceneInstId = context.getAcceptRequest().getSceneInstId();
        Map<String ,Object> tableMap = getTable(sceneInstId, moduleId,false);
        startRentInfo.setIsEdit("T");
        startRentInfo.setModuleType(LocalKeyConsts.MODULE_TYPE_TABLE);
        startRentInfo.setTableProdAttr(tableMap);
        return Collections.singletonList(startRentInfo);
    }

    @Override
    public List<? extends ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {

        StartRentInfoModuleVO startRentInfo = ((SceneNewOfferSeneVO) context.getSceneVo()).getStartRentInfo();
        String moduleId = sceneModule.getKiteModule().getModuleId();
        String sceneInstId = context.getAcceptRequest().getSceneInstId();
        Map<String ,Object> tableMap = getTable(sceneInstId, moduleId,false);
        startRentInfo.setIsEdit("T");
        startRentInfo.setModuleType(LocalKeyConsts.MODULE_TYPE_TABLE);
        startRentInfo.setTableProdAttr(tableMap);
        return Collections.singletonList(startRentInfo);
    }

    public Map<String ,Object> getTable(String sceneInstId, String moduleId ,boolean previewFlag){
        Map<String ,Object> tableMap = new HashMap();
        List<KiteAttr> commonAttrs = querySceneInstService.listCommonAttrsByModuleId(sceneInstId, moduleId);
        if(!KiteListUtils.isEmpty(commonAttrs)) {
            List tableColList = new ArrayList();
            commonAttrs.stream().forEach(attr -> {
                if(KiteStringUtils.isEqual(attr.getObjId(),"1")){
                    Map tableCol = new HashMap();
                    tableCol.put("dataIndex", attr.getFieldName());
                    tableCol.put("title", attr.getCname());
                    tableColList.add(tableCol);
                }
            });
            Map accMapLocation = new HashMap();
            accMapLocation.put("dataIndex", "userLocation");
            accMapLocation.put("title", "用户归属");

            if (!BatchAcceptUtil.isBatchStartRent(sceneInstId)) {
                Map accMap = new HashMap();
                accMap.put("dataIndex", "accNum");
                accMap.put("title", "业务号码");
                tableColList.add(1, accMap);
                tableColList.add(2, accMapLocation);
            }

            if(!previewFlag){
                Map tableCol = new HashMap();
                tableCol.put("dataIndex","ctrl");
                tableCol.put("title","操作");
                tableColList.add(tableCol);
            }

            tableMap.put("tableCol", tableColList);
            List<Map<String, Object>> tableValueList = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            KiteAttr accNumAttr = querySceneInstService.getCommonAttr(sceneInstId, "business_number");
            if(Objects.nonNull(accNumAttr)){
                map.put("accNum",accNumAttr.getValue());
            }

            Map<String, Object> extParameter = querySceneInstService.getExtParameter(sceneInstId);
            String orderId;
            Map<String, Object> worksheetData = (Map<String, Object>) extParameter.get("worksheetData");
            if (BatchAcceptUtil.isBatchStartRent(sceneInstId)) {
                Map<String, Object> orderInfo = querySceneInstService.getExtParameterValue(sceneInstId, "batchOrderInfo");
                orderId = KiteMapUtils.getString(orderInfo, "rootOrderId");
            }
            else {
                orderId = KiteMapUtils.getStrValue(worksheetData,"orderId");
            }

            map.put("orderId", orderId);
            String userRegionInfo = getUserRegionInfo(sceneInstId);
            map.put("userLocation", userRegionInfo);
            map.put("orderTache", KiteMapUtils.getStrValue(worksheetData,"nodeName"));
            map.put("taskName", KiteMapUtils.getStrValue(worksheetData,"taskName"));
            map.put("offerName", KiteMapUtils.getStrValue(worksheetData,"goodsName"));
            map.put("goodsType", KiteMapUtils.getStrValue(worksheetData,"goodsNodeName"));
            // 批量受理起租详情页，起租按钮改为查看
            if (Objects.nonNull(querySceneInstService.getExtParameterValue(sceneInstId, "batchNodeId"))) {
                map.put("ctrl", Stream.of("查看").collect(Collectors.toList()));
            }
            else {
                map.put("ctrl", Stream.of("起租").collect(Collectors.toList()));
            }
            tableValueList.add(map);
            if(!KiteListUtils.isEmpty(tableValueList)){
                tableMap.put("tableValue", tableValueList);
            }
        }
        return  tableMap;
    }

    public String getUserRegionInfo(String sceneInstId){
        String  userRegionInfo = "";
        ContextCustDTO custDTO1 = KiteWebContext.getContext().getCust();
        CuccContextCustDTO cuccContextCustDTO = KiteBeanUtils.transform(custDTO1, CuccContextCustDTO.class);
        if (Objects.nonNull(cuccContextCustDTO)) {
            List<String> regionCodes = new ArrayList<>();
            if (KiteStringUtils.isNotEmpty(cuccContextCustDTO.getProvinceCode())) {
                regionCodes.add(cuccContextCustDTO.getProvinceCode());

                if (KiteStringUtils.isNotEmpty(cuccContextCustDTO.getEparchyCode()) || KiteStringUtils.isNotEmpty(cuccContextCustDTO.getLanId())) {
                    regionCodes.add(KiteStringUtils.isNotEmpty(cuccContextCustDTO.getEparchyCode())?cuccContextCustDTO.getEparchyCode():cuccContextCustDTO.getLanId());

                    if (KiteStringUtils.isNotEmpty(cuccContextCustDTO.getRegionId())) {
                        regionCodes.add(cuccContextCustDTO.getRegionId());
                    }
                }
            }
            userRegionInfo = getValueDesc(KiteStringUtils.join(regionCodes, SymbolConsts.COMMA));
        }
        return userRegionInfo;
    }

    private String getValueDesc(String value) {
        if (KiteStringUtils.isEmpty(value)) {
            return "";
        }
        String[] regionCodes = KiteStringUtils.split(value, SymbolConsts.COMMA);
        List<String> regionNames = Arrays.stream(regionCodes).map(s -> {
            UnicomRegion region = unicomRegionService.getRegion(s);
            return Objects.nonNull(region) ? region.getRegionName() : "";
        }).collect(Collectors.toList());
        return KiteStringUtils.join(regionNames, SymbolConsts.HYPHEN);
    }

}
